import React, { useState, useRef, useEffect } from "react";

// Services
import AuthService from "../../services/auth.service.js";
import userService from "../../services/user.service.js";

// Components
import { Link } from "react-router-dom";
import { Redirect } from "react-router-dom";
import {
  Button,
  Card,
  CardBody,
  Form,
  FormGroup,
  Col,
  Input,
  Alert,
} from "reactstrap";
import {  Check, X } from "react-feather";
import { Popover } from 'antd';

// Constants
const colors = "danger";

/*
* This is the company login / signup page
*
* This page will need to change depending on the user (Company) email address
* each company logo should be displayed with their primary & secondary colours
*
* TODO: Implement & connect to production
* TODO: Needs to be Tested
* */

const CompanyLoginPanel = (props) => {
  const [state, setstate] = useState("");
  const formCompany = useRef();

  const [companyEmailLogin, setCompanyEmailLogin] = useState("");
  const [companyPasswordLogin, setCompanyPasswordLogin] = useState("");

  const [messageCompany, setMessageCompany] = useState("");
  const [messageCompanySignup, setMessageCompanySignup] = useState("");
  const [passwordscore, setPasswordscore] = useState();
  const formUserSignup = useRef();



  const [emailSignup, setEmailSignup] = useState("");

  const [firstNameSignup, setFirstNameSignup] = useState("");
  const [lastNameSignup, setLastNameSignup] = useState("");
  const [jobRoles, setJobRoles] = useState("");
  const [currentJobRole, setCurrentJobRole] = useState(0);
  const [passwordSignup, setPasswordSignup] = useState("");
  //password rule
  const [PasspasswordRule1, setPasspasswordRule1] = useState(false);
  const [PasspasswordRule2, setPasspasswordRule2] = useState(false);
  const [PasspasswordRule3, setPasspasswordRule3] = useState(false);
  const [PasspasswordRule4, setPasspasswordRule4] = useState(false);


  const onChangePasswordSignup = (e) => {
      let passwordRule1 = /.{8,}/;
      let passwordRule2 = /[A-Z]/;
      let passwordRule3 = /[a-z]/;
      let passwordRule4 = /\d/;
      const password = e.target.value;
      if(passwordRule1.test(password)){
          setPasspasswordRule1(true)
      }else{
          setPasspasswordRule1(false)
      }
      if(passwordRule2.test(password)){
          setPasspasswordRule2(true)
      }else{
          setPasspasswordRule2(false)
      }
      if(passwordRule3.test(password)){
          setPasspasswordRule3(true)
      }else{
          setPasspasswordRule3(false)
      }
      if(passwordRule4.test(password)){
          setPasspasswordRule4(true)
      }else{
          setPasspasswordRule4(false)
      }
      setPasswordSignup(password);
  };

  const onChangeFirstName = (e) => {
      const firstName = e.target.value;
      setFirstNameSignup(firstName);
  };

  const onChangeLastName = (e) => {
      const lastName = e.target.value;
      setLastNameSignup(lastName);
  };

  const onChangeEmailSignup = (e) => {
      const email = e.target.value;
      setEmailSignup(email);
  };
  const onChangeJobRole = (e) => {
      const jobRole = e.target.value;
      setCurrentJobRole(jobRole);
  };

  const [visible1, setVisible1] = useState(true);
  const [visible2, setVisible2] = useState(true);
  const [loading, setLoading] = useState(false);

  const onDismiss1 = () => setVisible1(false);
  const onDismiss2 = () => setVisible2(false);

  const onChangeCompanyEmailLogin = (e) => {
    const username = e.target.value;
    setCompanyEmailLogin(username);
  };

  const onChangeCompanyPasswordLogin = (e) => {
    const password = e.target.value;
    setCompanyPasswordLogin(password);
  };

  const user = AuthService.getCurrentUser();
  var currentCompany = AuthService.getCurrentCompany();

  //if  user is logged in take to the user dashboard
  if (user) {
    props.history.push("/dashboard/default");
    window.location.reload();
  }
   // Fetch job roles from API & populate dropdown
   useEffect(() => {
    if (jobRoles.length === 0) {
        userService.GetJobRoles().then((response) => {
            if (response !== null) {
                setJobRoles(response);
            }
        });
    }
});
  //setting the state when the file is being uploaded (company logo)
  const onCompanyLogoChange = (event) => {
    // Update the state
    setstate({ file: event.target.files[0] });
  };
  const handleLogin = (e) => {
    e.preventDefault();
    setMessageCompany("");
    setLoading(true);
    if (companyEmailLogin !== "" && companyPasswordLogin !== "") {
        AuthService.loginUser(companyEmailLogin, companyPasswordLogin).then((response) => {
          if(response.password_reset_mandatory === "True"){
              window.sessionStorage.setItem("password_reset_mandatory",companyEmailLogin);
              props.history.push("/auth/change-password");
          }else{
            if (response.Message === "") {
                setLoading(false);
                props.history.push("/dashboard/default");
                //   window.location.reload();
            } else {
                setLoading(false);
                setVisible2(true)
                setMessageCompany(response.Message);
                props.history.push("/");
            }
          }
        });
    } else {
        setLoading(false);
        setVisible2(true)
        setMessageCompany("Kindly fill all the fields");
    }
};
  const handleSignup = (e) => {
    e.preventDefault();
    setMessageCompanySignup("");

    if (
        passwordSignup !== "" &&
        firstNameSignup !== "" &&
        lastNameSignup !== "" &&
        emailSignup !== "" &&
        currentJobRole !== 0
    ) {
        if(!PasspasswordRule1 || !PasspasswordRule2 || !PasspasswordRule3|| !PasspasswordRule4){
          setVisible1(true)
          setMessageCompanySignup(
                    "Password is too weak. You must use a stronger password to continue."
                );
            }else{
                AuthService.registerUser(
                    firstNameSignup,
                    lastNameSignup,
                    emailSignup,
                    passwordSignup,
                    currentJobRole
                ).then((response) => {
                    if (response.data.Status === "Success") {
                        props.history.push("/thankyou");
                        window.location.reload();
                    } else {
                      setVisible1(true)
                      setMessageCompanySignup(response.data.Message);
                        props.history.push("/");
                    }
                });
            }
    } else {
      setVisible1(true)
        setMessageCompanySignup(
            "All the fields are required, kindly fill all the fields"
        );
    }
  };
  // const handleCompanySignup = (e) => {
  //   e.preventDefault();

  //   setMessageCompanySignup("");

  //   if (
  //     companyNameSignup !== "" &&
  //     companyMessageSignup !== "" &&
  //     companyPhoneSignup !== "" &&
  //     companyContactPersonSignup !== "" &&
  //     companyEmailSignup !== ""
  //   ) {
  //     AuthService.registerCompany(
  //       companyNameSignup,
  //       companyMessageSignup,
  //       companyEmailSignup,
  //       companyPhoneSignup,
  //       companyContactPersonSignup
  //     ).then((response) => {
  //       if (response.data.Status === "Success") {
  //         props.history.push("/thankyou");
  //         window.location.reload();
  //       } else {
  //         setVisible1(true)
  //         setMessageCompanySignup(response.data.Message);
  //         props.history.push("/companyLogin");
  //       }
  //     });
  //   } else {
  //     setVisible1(true)
  //     setMessageCompanySignup("Kindly fill all the fields");
  //   }
  // };
  if (currentCompany === null) {
    return (
      <React.Fragment>
        <Col sm="5" md="8" lg="6" className="mx-auto p-0">
          <Card className="h-100 shadow-lg">
            <div className="signup-card">
                <CardBody>
                    <div className="mt-7 mb-7 ml-7 mr-7 pt-4 pl-4 pr-4 pb-4">
                        <div className="text-center">
                            <h2 className="h2-black-heading mb-4">Sign up</h2>
                        </div>
                        <Form onSubmit={handleSignup} ref={formUserSignup}>
                            <FormGroup>
                                <Input
                                    bsSize="lg"
                                    type="text"
                                    name="firstname"
                                    placeholder="First name"
                                    value={firstNameSignup}
                                    onChange={onChangeFirstName}
                                />
                            </FormGroup>
                            <FormGroup>
                                <Input
                                    bsSize="lg"
                                    type="text"
                                    name="lastname"
                                    placeholder="Last name"
                                    value={lastNameSignup}
                                    onChange={onChangeLastName}
                                />
                            </FormGroup>
                            <FormGroup>
                                <select
                                    className="custom-select"
                                    value={currentJobRole}
                                    onChange={onChangeJobRole}
                                >
                                    <option key={0} value={0} disabled>
                                        Job Role
                                    </option>
                                    {jobRoles &&
                                    jobRoles.length > 0 &&
                                    jobRoles.map((schema) => {
                                        return (
                                            <option key={schema.id} value={schema.id}>
                                                {schema.name}
                                            </option>
                                        );
                                    })}
                                </select>
                            </FormGroup>
                            <FormGroup>
                                <Input
                                    bsSize="lg"
                                    type="email"
                                    name="email"
                                    placeholder="Email"
                                    value={emailSignup}
                                    onChange={onChangeEmailSignup}
                                />
                            </FormGroup>

                            <FormGroup>
                                <Popover
                                  content={
                                      <div>
                                          <p>{PasspasswordRule1? <Check size={18} color="#22db62"/>:<X size={18} color="#eb1414"/>}At least 8 characters long.</p>
                                          <p>{PasspasswordRule2? <Check size={18} color="#22db62"/>:<X size={18} color="#eb1414"/>}Have at least one uppercase letter.</p>
                                          <p>{PasspasswordRule3? <Check size={18} color="#22db62"/>:<X size={18} color="#eb1414"/>}Have at least one lowercase letter.</p>
                                          <p>{PasspasswordRule4? <Check size={18} color="#22db62"/>:<X size={18} color="#eb1414"/>}Have at least one number.</p>
                                      </div>}
                                  placement="right"
                                  title={
                                      <span>
                                          Password requirements:
                                      </span>
                                  }
                                  trigger="focus">
                                 <Input
                                    type="password"
                                    bsSize="lg"
                                    placeholder="Password"
                                    name="password"
                                    // maxLength={10}
                                    value={passwordSignup}
                                    onChange={onChangePasswordSignup}
                                    onFocus={onChangePasswordSignup}
                                />
                              </Popover>
                               
                            </FormGroup>
                            {/* <Link to="/thankyou"> */}
                            <button className="btn btn-primary ml-auto mr-0 d-block font-weight-bold">
                                Signup
                            </button>
                            {/* </Link> */}
                            <div className={"mt-3"}>
                            {messageCompanySignup && (
                              <Alert color={colors} isOpen={visible1} toggle={onDismiss1}> 
                                <div className="alert-message"  style={{padding:'0.95rem 1.2rem'}}>
                                  <strong>{messageCompanySignup}</strong>
                                </div>
                              </Alert>
                            )}
                            </div>
                        </Form>
                    </div>
                </CardBody>
            </div>
          </Card>
        </Col>

        <Col sm="5" md="8" lg="6" className="mx-auto p-0">
          <Card className="h-100 shadow-lg bg-primary">
            <div className="othercard">
              <CardBody>
                <div className=" mr-7 ml-7 mb-7 p-4" style={{marginTop:'7rem'}}>
                  <div className="text-center">
                    <h2 className="h2-heading text-white">Login</h2>
                  </div>
                  <Form onSubmit={handleLogin} ref={formCompany}>
                    <FormGroup>
                      <Input
                        bsSize="lg"
                        type="email"
                        name="companyName"
                        placeholder="Company Email"
                        onChange={onChangeCompanyEmailLogin}
                      />
                    </FormGroup>
                    <FormGroup>
                      <Input
                        bsSize="lg"
                        type="password"
                        name="password"
                        placeholder="Password"
                        onChange={onChangeCompanyPasswordLogin}
                      />
                    </FormGroup>

                    <div className="signin-div">
                      {/* <Link to="/dashboard/default"> */}
                      <button className="btn btn-outline-primary text-white border-white d-block ml-auto mr-0 col-3 font-weight-bold" disabled={loading}>
                          {loading && (<span className="spinner-border spinner-border-sm"></span>)}
                          <span>Login</span>
                      </button>
                      {/* <Button className="btnBlue">login</Button> */}
                      {/* </Link> */}
                    </div>
                    <div className="forgot-div">
                        <small>
                            <Link
                                className="btn btn-link text-white"
                                to="/auth/reset-password"
                            >
                                Forgot password?
                            </Link>
                        </small>
                    </div>
                  </Form>
                  <div>
                    {messageCompany && (
                      <Alert color={colors} isOpen={visible2} toggle={onDismiss2}>
                        <div className="alert-message"  style={{padding:'0.95rem 1.2rem'}}>
                          <strong>{messageCompany}</strong>
                        </div>
                      </Alert>
                    )}
                  </div>
                </div>
              </CardBody>
            </div>
          </Card>
        </Col>
      </React.Fragment>
    );
  } else {
    return (
      <div>
        <Redirect to="/dashboard/default" />
      </div>
    );
  }
};
export default CompanyLoginPanel;
